<template>
  <div class="emotion-tracker">
    <!-- 顶部导航栏 -->
    <div class="navbar">
      <div class="nav-back" @click="$router.go(-1)">
        <i class="fas fa-chevron-left"></i>
      </div>
      <div class="nav-title">每日情绪记录</div>
      <div class="nav-placeholder"></div>
    </div>

    <div class="header">
      <h1 class="title">
        <span class="heart-icon">❤️</span>
        每日情绪记录
      </h1>
      <p class="subtitle">记录心情，了解自我，提升情绪健康</p>
    </div>

    <!-- 表单容器 -->
    <form class="form-container" @submit.prevent="submitForm">
      <!-- 基本信息卡片 -->
      <div class="card fade-in">
        <div class="card-header">
          <h2 class="card-title">
            <span class="icon">📅</span>
            基本信息
          </h2>
        </div>

        <!-- 日期选择 -->
        <div class="form-group">
          <label class="form-label"
            >记录日期 <span class="required">*</span></label
          >
          <input
            type="date"
            class="date-input"
            v-model="formData.recordDate"
            :class="{ error: showValidationErrors && !formData.recordDate }"
          />
          <div
            v-if="showValidationErrors && !formData.recordDate"
            class="error-message"
          >
            请选择记录日期
          </div>
        </div>

        <!-- 主导情绪 -->
        <div class="form-group">
          <label class="form-label"
            >今日主导情绪 <span class="required">*</span></label
          >
          <div class="emotion-grid">
            <label
              v-for="emotion in emotions"
              :key="emotion.value"
              class="emotion-option"
              :class="{
                selected: formData.emotion === emotion.value,
                error: showValidationErrors && !formData.emotion,
              }"
              @click="selectEmotion(emotion.value)"
            >
              <input
                type="radio"
                name="emotion"
                :value="emotion.value"
                class="hidden-radio"
                v-model="formData.emotion"
              />
              <div class="emotion-icon" :class="emotion.class">
                {{ emotion.icon }}
              </div>
              <div>{{ emotion.label }}</div>
            </label>
          </div>
          <div
            v-if="showValidationErrors && !formData.emotion"
            class="error-message"
          >
            请选择今日主导情绪
          </div>
        </div>

        <!-- 情绪强度 -->
        <div class="form-group">
          <label class="form-label"
            >情绪强度 <span class="required">*</span></label
          >
          <input
            type="range"
            min="1"
            max="10"
            class="intensity-slider"
            v-model="formData.intensity"
          />
          <div class="intensity-labels">
            <span>轻微</span>
            <span>中等</span>
            <span>强烈</span>
          </div>
          <div class="intensity-value">
            当前强度: {{ formData.intensity }}/10
          </div>
        </div>
      </div>

      <!-- 事件记录卡片 -->
      <div class="card">
        <div class="card-header">
          <h2 class="card-title">
            <span class="icon">📋</span>
            今日主要事件 <span class="required">*</span>
          </h2>
        </div>

        <textarea
          class="event-textarea"
          :class="{ error: showValidationErrors && !formData.mainEvent.trim() }"
          placeholder="请描述今天发生的主要事件，它引发了什么情绪，以及您当时的想法..."
          v-model="formData.mainEvent"
        ></textarea>
        <div
          v-if="showValidationErrors && !formData.mainEvent.trim()"
          class="error-message"
        >
          请填写今日主要事件
        </div>
      </div>

      <!-- 三件好事卡片 -->
      <div class="card">
        <div class="card-header">
          <h2 class="card-title">
            <span class="icon">⭐</span>
            今日三件好事 <span class="required">*</span>
          </h2>
        </div>

        <div class="good-things-list">
          <div
            v-for="(item, index) in formData.goodThings"
            :key="index"
            class="good-thing-item"
          >
            <div class="good-thing-number">{{ index + 1 }}</div>
            <input
              type="text"
              :placeholder="`第${index + 1}件好事...`"
              class="good-thing-input"
              :class="{ error: showValidationErrors && !item.trim() }"
              v-model="formData.goodThings[index]"
              @focus="clearValidation"
            />
          </div>
        </div>
        <div
          v-if="showValidationErrors && !allGoodThingsFilled"
          class="error-message"
        >
          请填写完整三件好事
        </div>
      </div>

      <!-- 提交按钮 -->
      <button
        type="submit"
        class="submit-btn"
        :disabled="isSubmitting"
        :class="{ loading: isSubmitting }"
      >
        <span v-if="!isSubmitting" class="btn-icon">💾</span>
        <span v-else class="loading-spinner"></span>
        {{ isSubmitting ? "提交中..." : "保存情绪记录" }}
      </button>
    </form>

    <!-- 消息提示 -->
    <div v-if="showMessage" :class="`message ${messageType}`">
      {{ messageText }}
    </div>
  </div>
</template>

<script>
import { practiceCheckin, dailyEmotionRecord } from "@/api/user";

export default {
  name: "EmotionTracker",
  data() {
    return {
      formData: {
        recordDate: "",
        emotion: "",
        intensity: 5,
        mainEvent: "",
        goodThings: ["", "", ""],
      },
      emotions: [
        { value: "平静", label: "平静", icon: "☮️", class: "calm" },
        { value: "焦虑", label: "焦虑", icon: "🌀", class: "anxious" },
        { value: "悲伤", label: "悲伤", icon: "🌧️", class: "sad" },
        { value: "喜悦", label: "喜悦", icon: "😄", class: "happy" },
        { value: "愤怒", label: "愤怒", icon: "🔥", class: "angry" },
        { value: "疲惫", label: "疲惫", icon: "🌙", class: "tired" },
      ],
      showValidationErrors: false,
      showMessage: false,
      messageText: "",
      messageType: "",
      taskData: null,
      isSubmitting: false,
    };
  },
  computed: {
    allGoodThingsFilled() {
      return this.formData.goodThings.every((item) => item.trim() !== "");
    },
    isValidForm() {
      return (
        this.formData.recordDate &&
        this.formData.emotion &&
        this.formData.mainEvent.trim() &&
        this.allGoodThingsFilled
      );
    },
  },
  created() {
    if (this.$route.query.task) {
      try {
        this.taskData = JSON.parse(this.$route.query.task);
      } catch (error) {
        console.error("解析任务数据失败:", error);
      }
    }
  },
  mounted() {
    // 设置默认日期为今天
    const today = new Date();
    const formattedDate = today.toISOString().split("T")[0];
    this.formData.recordDate = formattedDate;
  },
  methods: {
    selectEmotion(emotion) {
      this.formData.emotion = emotion;
      this.clearValidation();
    },

    clearValidation() {
      this.showValidationErrors = false;
    },

    async submitForm() {
      // 显示验证错误
      this.showValidationErrors = true;

      // 验证表单
      if (!this.isValidForm) {
        this.showMessageFunc("请填写所有必填字段", "error");
        return;
      }

      // 防止重复提交
      if (this.isSubmitting) return;
      this.isSubmitting = true;

      try {
        // 构建提交数据
        const submitData = {
          personalPracticeId: this.taskData?.id || "",
          emotion: this.getEmotionCode(this.formData.emotion),
          strength: parseInt(this.formData.intensity) * 10, // 转换为百分比
          mainEvents: this.formData.mainEvent.trim(),
          threeGood: this.formData.goodThings
            .map((item, index) => `${index + 1}.${item.trim()}`)
            .join(","),
          recordTime: `${this.formData.recordDate} ${
            new Date().toTimeString().split(" ")[0]
          }`,
          createTime: new Date()
            .toLocaleString("sv-SE")
            .replace("T", " ")
            .split(".")[0],
        };

        console.log("提交的数据:", submitData);

        // 真实提交
        const res = await dailyEmotionRecord(submitData);

        if (res.code === 200) {
          this.showMessageFunc("情绪记录已保存！", "success");

          // 完成训练
          await this.completeTraining();

          // 重置表单并返回
          setTimeout(() => {
            this.resetForm();
            this.$router.go(-1);
          }, 1500);
        } else {
          throw new Error(res.message || "保存失败");
        }
      } catch (error) {
        console.error("提交失败:", error);
        this.showMessageFunc(error.message || "保存失败，请重试", "error");
      } finally {
        this.isSubmitting = false;
      }
    },

    getEmotionCode(emotion) {
      const emotionMap = {
        平静: 1,
        焦虑: 2,
        悲伤: 3,
        喜悦: 4,
        愤怒: 5,
        疲惫: 6,
      };
      return emotionMap[emotion] || 0;
    },

    async completeTraining() {
      if (!this.taskData) return;

      try {
        const data = {
          personalPracticeId: this.taskData.id,
          practiceTime: this.taskData.practiceTime,
          userId: localStorage.getItem("userId"),
        };

        const res = await practiceCheckin(data);
        if (res.code !== 200) {
          console.error("完成训练失败:", res.message);
        }
      } catch (error) {
        console.error("完成训练请求失败:", error);
      }
    },

    showMessageFunc(text, type) {
      this.messageText = text;
      this.messageType = type;
      this.showMessage = true;

      // 3秒后移除消息
      setTimeout(() => {
        this.showMessage = false;
      }, 3000);
    },

    resetForm() {
      const today = new Date().toISOString().split("T")[0];
      this.formData = {
        recordDate: today,
        emotion: "",
        intensity: 5,
        mainEvent: "",
        goodThings: ["", "", ""],
      };
      this.showValidationErrors = false;
    },
  },
};
</script>

<style scoped>
/* 全局样式 */
.emotion-tracker {
  background: linear-gradient(135deg, #e0f2fe 0%, #e0e7ff 100%);
  min-height: 100vh;
  padding: 16px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, sans-serif;
  color: #374151;
  box-sizing: border-box;
}

/* 导航栏 */
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  z-index: 1000;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.nav-back {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #eef0ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #5b67ff;
  cursor: pointer;
  transition: all 0.3s ease;
  touch-action: manipulation;
}

.nav-back:hover {
  background: #e0e0e0;
}

.nav-title {
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.nav-placeholder {
  width: 40px;
}

/* 头部标题 */
.header {
  text-align: center;
  padding: 32px 0;
  margin-top: 50px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin: 0;
}

.heart-icon {
  background-color: #e0e7ff;
  color: #4f46e5;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.subtitle {
  color: #6b7280;
  margin-top: 8px;
}

/* 表单容器 */
.form-container {
  max-width: 480px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 卡片样式 */
.card {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1),
    0 4px 6px -2px rgba(0, 0, 0, 0.05);
  border: 1px solid #f3f4f6;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f3f4f6;
  padding-bottom: 12px;
  margin-bottom: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
}

.icon {
  color: #4f46e5;
}

.required {
  color: #ef4444;
  margin-left: 4px;
}

/* 表单组 */
.form-group {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  color: #374151;
  margin-bottom: 8px;
  font-weight: 500;
}

/* 日期输入 */
.date-input {
  width: 80%;
  padding: 12px 16px;
  background-color: #f9fafb;
  border: 1px solid #d1d5db;
  border-radius: 12px;
  color: #374151;
  font-weight: 500;
  font-size: 16px;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.date-input:focus {
  outline: none;
  border-color: #4f46e5;
  background-color: white;
}

.date-input.error {
  border-color: #ef4444;
  background-color: #fef2f2;
}

/* 情绪网格 */
.emotion-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-top: 12px;
}

.emotion-option {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.emotion-option:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.emotion-option.selected {
  border-color: #4f46e5;
  background-color: #eef2ff;
  box-shadow: 0 4px 6px -1px rgba(79, 70, 229, 0.2);
}

.emotion-option.error {
  border-color: #ef4444;
}

.hidden-radio {
  display: none;
}

.emotion-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

/* 情绪强度滑块 */
.intensity-slider {
  width: 100%;
  height: 8px;
  background: linear-gradient(to right, #10b981, #f59e0b, #ef4444);
  border-radius: 4px;
  outline: none;
  -webkit-appearance: none;
  margin: 16px 0 8px;
}

.intensity-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: white;
  border: 3px solid #4f46e5;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  cursor: pointer;
}

.intensity-labels {
  display: flex;
  justify-content: space-between;
  color: #6b7280;
  font-size: 14px;
  margin-top: 4px;
}

.intensity-value {
  text-align: center;
  color: #4f46e5;
  font-weight: 600;
  margin-top: 8px;
}

/* 事件文本区域 */
.event-textarea {
  width: 100%;
  padding: 16px;
  background-color: #f9fafb;
  border: 1px solid #d1d5db;
  border-radius: 12px;
  min-height: 120px;
  box-sizing: border-box;
  font-family: inherit;
  resize: vertical;
  transition: all 0.3s ease;
}

.event-textarea:focus {
  outline: none;
  border-color: #4f46e5;
  background-color: white;
}

.event-textarea.error {
  border-color: #ef4444;
  background-color: #fef2f2;
}

/* 三件好事 */
.good-things-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.good-thing-item {
  position: relative;
  padding-left: 32px;
}

.good-thing-number {
  position: absolute;
  left: 0;
  top: 0;
  width: 24px;
  height: 24px;
  background-color: #eef2ff;
  color: #4f46e5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
}

.good-thing-input {
  width: 80%;
  padding: 8px 12px;
  border: none;
  border-bottom: 1px solid #d1d5db;
  outline: none;
  font-family: inherit;
  font-size: 16px;
  transition: all 0.3s ease;
}

.good-thing-input:focus {
  border-bottom: 2px solid #4f46e5;
}

.good-thing-input.error {
  border-bottom: 2px solid #ef4444;
}

/* 错误消息 */
.error-message {
  color: #ef4444;
  font-size: 14px;
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.error-message::before {
  content: "⚠️";
  font-size: 12px;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  padding: 16px;
  background: linear-gradient(to right, #4f46e5, #4338ca);
  color: white;
  border: none;
  border-radius: 12px;
  font-weight: 600;
  font-size: 18px;
  box-shadow: 0 10px 15px -3px rgba(79, 70, 229, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  position: relative;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-4px);
  box-shadow: 0 15px 20px -3px rgba(79, 70, 229, 0.4);
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.submit-btn.loading {
  background: linear-gradient(to right, #a5b4fc, #818cf8);
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid transparent;
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.btn-icon {
  font-size: 16px;
}

/* 消息提示 */
.message {
  position: fixed;
  top: 45%;
  left: 50%;
  transform: translateX(-50%);
  color: white;
  padding: 12px 24px;
  border-radius: 24px;
  font-weight: 600;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
  z-index: 50;
  animation: fadeIn 0.5s ease-out;
}

.message.success {
  background-color: #10b981;
}

.message.error {
  background-color: #ef4444;
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .emotion-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .card {
    padding: 16px;
  }

  .title {
    font-size: 20px;
  }

  .heart-icon {
    width: 36px;
    height: 36px;
    font-size: 16px;
  }

  .date-input,
  .good-thing-input {
  }
}
</style>
